"""
Case Type   : SQL语法
Case Name   : 关闭checkpoint后,创建段页式表
Create At   : 2023/02/20
Owner       : cr13
Description :
    1.建表
    2.插入/修改表数据
    3.清理环境
Expect      :
    1.成功
    2.成功
    3.成功
History     :
"""

import os
import unittest
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Common import Common
from testcase.utils.Logger import Logger


class SQL(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.constant = Constant()
        self.com = Common()
        self.commsh = CommonSH('PrimaryDbUser')
        self.tbname = 't_partition_truncate_0326'
        self.enable_incremental_checkpoint = self.com.show_param(
            'enable_incremental_checkpoint')
        guc_res = self.commsh.execute_gsguc(
                'set', self.constant.GSGUC_SUCCESS_MSG,
                'enable_incremental_checkpoint=off')
        self.assertTrue(guc_res, '执行失败')
        result = self.commsh.restart_db_cluster()
        self.assertTrue(result, '执行失败')

    def test_partition_table(self):
        text = "----step1:建表 expect:成功----"
        self.log.info(text)
        sql_cmd = f"drop table if exists {self.tbname} cascade;" \
            f"create table {self.tbname}(id int) with (segment=on);"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        self.assertIn(self.constant.TABLE_DROP_SUCCESS, result, '执行失败' +
                      text)
        self.assertIn(self.constant.CREATE_TABLE_SUCCESS, result, '执行失败' +
                      text)

        text = "----step2:插入/修改表数据 expect:成功----"
        self.log.info(text)
        sql_cmd = f"insert into {self.tbname} values(generate_series(1,10));" \
            f"update {self.tbname} set id = 10 where id < 10;"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        self.assertIn(self.constant.UPDATE_SUCCESS_MSG, result,
                      '执行失败' + text)
        self.assertIn(self.constant.INSERT_SUCCESS_MSG, result,
                      '执行失败' + text)

    def tearDown(self):
        text = '-----step3:清理环境 expect:成功-----'
        self.log.info(text)
        sql_cmd = f"drop table {self.tbname} cascade;"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        self.assertIn(self.constant.TABLE_DROP_SUCCESS, result, '执行失败' +
                      text)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
